package busmap.main;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
public class Map extends MapActivity  {
	MapView mapView;
	GeoPoint From_GeoPoint = null;
	GeoPoint To_GeoPoint = null;
	private Drawable drawable;
    private GeoPoint point = new GeoPoint( (int) (10.780655 *1E6) ,(int) (106.6691140 * 1E6));
    private MyOverlays itemizedoverlay;
	private MyLocationOverlay myLocationOverlay;
	private LocationManager locationManager;
	private GeoUpdateHandler GPSListener = new GeoUpdateHandler();
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.layout.menu, menu);
	 
	    return true;
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
	    switch (item.getItemId()) {
	        case R.id.map_search:
	            //search on the Map
	        	map_search();
	            return true;
	        case R.id.map_refresh:
	        	map_refresh();
	        	//refresh map
	        	return true;
	        case R.id.map_mylocation:
	        	//update my location
	        	map_mylocation();
	        	return true;
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}
	private void map_refresh(){
		mapView.getController().animateTo(point);
		mapView.getController().setZoom(14);	
		mapView.getOverlays().clear();
		myLocationOverlay.disableMyLocation();
		myLocationOverlay.disableCompass();
		myLocationOverlay = new MyLocationOverlay(this, mapView);
		mapView.getOverlays().add(myLocationOverlay);
		mapView.invalidate();
	}
	private void map_search(){
		
	}
	private void map_mylocation(){
		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, GPSListener);
		myLocationOverlay.enableMyLocation();
		myLocationOverlay.enableCompass();
	}
	@Override
	public void onCreate(Bundle savedInstanceState) {		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.map);
		mapView = (MapView) findViewById(R.id.googlemap);	   
		mapView.setBuiltInZoomControls(true);
		mapView.getController().animateTo(point);
		mapView.getController().setZoom(14);	   
		mapView.getOverlays().clear();	   
		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		myLocationOverlay = new MyLocationOverlay(this, mapView);
		mapView.getOverlays().add(myLocationOverlay);
		drawable = this.getResources().getDrawable(R.drawable.marker);
		itemizedoverlay = new MyOverlays(this, drawable);
		mapView.invalidate();		
	}
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}
	private void createMarker(GeoPoint p) {
		if(p == null)
			p = mapView.getMapCenter();
		OverlayItem overlayitem = new OverlayItem(p, "", "");
		itemizedoverlay.addOverlay(overlayitem);
		if (itemizedoverlay.size() > 0) {
			mapView.getOverlays().add(itemizedoverlay);
		}
	}
	@Override
	protected void onResume() {
		super.onResume();
		myLocationOverlay.enableMyLocation();
		myLocationOverlay.enableCompass();
	}
	@Override
	protected void onPause() {
		super.onResume();
		myLocationOverlay.disableMyLocation();
		myLocationOverlay.disableCompass();
	}
	public class GeoUpdateHandler implements LocationListener {
		public void onLocationChanged(Location location) {
			int lat = (int) (location.getLatitude() * 1E6);
			int lng = (int) (location.getLongitude() * 1E6);
			GeoPoint point = new GeoPoint(lat, lng);
			mapView.getController() .animateTo(point); // mapController.setCenter(point);
			createMarker(point);	
			locationManager.removeUpdates(GPSListener);
			myLocationOverlay.disableMyLocation();
			myLocationOverlay.disableCompass();
		}
		public void onProviderDisabled(String provider) {
		}
		public void onProviderEnabled(String provider) {
		}
		public void onStatusChanged(String provider, int status, Bundle extras) {
		}
	}	
	public class MyOverlays extends ItemizedOverlay<OverlayItem> {
		private static final int maxNum = 5;
		private OverlayItem overlays[] = new OverlayItem[maxNum];
		private int index = 0;
		private boolean full = false;
		private Context context;
		private OverlayItem previousoverlay;
		public MyOverlays(Context context, Drawable defaultMarker) {
			super(boundCenterBottom(defaultMarker));
			this.context = context;
		}
		@Override
		protected OverlayItem createItem(int i) {
			return overlays[i];
		}

		@Override
		public int size() {
			if (full) {
				return overlays.length;
			} else {
				return index;
			}

		}
		public void addOverlay(OverlayItem overlay) {
			if (previousoverlay != null) {
				if (index < maxNum) {
					overlays[index] = previousoverlay;
				} else {
					index = 0;
					full = true;
					overlays[index] = previousoverlay;
				}
				index++;
				populate();
			}
			this.previousoverlay = overlay;
		}
		
		@Override
		public boolean onTap(GeoPoint p, MapView mapView) {
			// TODO Auto-generated method stub
	    	//Toast.makeText(getBaseContext(), p.getLatitudeE6() / 1E6 + " : " +  p.getLongitudeE6() / 1E6  , Toast.LENGTH_SHORT).show();
	    	final CharSequence[] items = {"Từ đây", "Đến đây","Trở về"};
	    	final GeoPoint Selected = p;
	    	String add = "";
	    	 Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());
	         try {
	                    List<Address> addresses = geoCoder.getFromLocation(
	                        p.getLatitudeE6()  / 1E6, 
	                        p.getLongitudeE6() / 1E6, 1);	 
	        
	                    if (addresses.size() > 0) 
	                    {
	                        for (int i=0; i<addresses.get(0).getMaxAddressLineIndex();i++)
	                           add += addresses.get(0).getAddressLine(i) + "\n";
	                    }	 
	                }
	        catch (IOException e) {                
	             e.printStackTrace();
	        }   	    	
	    	AlertDialog.Builder builder = new AlertDialog.Builder(Map.this);
	    	builder.setTitle(add);
	    	builder.setItems(items, new DialogInterface.OnClickListener() {
	    	    public void onClick(DialogInterface dialog, int item) {
	    	    	switch(item){
	    	    		case 1:
	    	    			From_GeoPoint = Selected;
	    	    			break;
	    	    		case 2:
	    	    			To_GeoPoint = Selected;
	    	    			break;
	    	    		case 3:
	    	    			break;
	    	    	}
	    	        Toast.makeText(getBaseContext(), items[item], Toast.LENGTH_SHORT).show();
	    	    }
	    	});
	    	AlertDialog alert = builder.create();    
	    	alert.show();
	    	return super.onTap(p, mapView);
		}
	}
}




